package com.yubest.shiro.service.shiro;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.crypto.SecureUtil;
import com.yubest.shiro.bean.UserInfo;
import com.yubest.shiro.consts.Consts;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.permission.AllPermission;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.*;

/**
 * 负责认证用户身份和对用户进行授权
 *
 * @Author: hweiyu
 * @Date: 2022/11/7 11:41
 */
public class MyRealm extends AuthorizingRealm {

    private Map<String, UserInfo> userCacheMap = new HashMap<>();

    public MyRealm() {
        this.initData();
    }

    /**
     * 模拟数据
     */
    public void initData() {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(1L);
        userInfo.setUsername("admin");
        userInfo.setPassword(SecureUtil.md5("123456"));
        //
        userInfo.setPermitCodeList(Arrays.asList(Consts.PERMIT_ALL));
        userCacheMap.put(userInfo.getUsername(), userInfo);

        UserInfo userInfo2 = new UserInfo();
        userInfo2.setId(1L);
        userInfo2.setUsername("test");
        userInfo2.setPassword(SecureUtil.md5("123456"));
        userInfo2.setPermitCodeList(Arrays.asList("testx", "test2", "info", "logout"));
        userCacheMap.put(userInfo2.getUsername(), userInfo2);
    }

    /**
     * 用户权限认证
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        UserInfo user = (UserInfo) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 放入权限信息
        if (CollectionUtil.isNotEmpty(user.getPermitCodeList())
                && user.getPermitCodeList().contains(Consts.PERMIT_ALL)) {
            // admin 账号，拥有所有权限
            authorizationInfo.addObjectPermission(new AllPermission());
        } else {
            authorizationInfo.addStringPermissions(user.getPermitCodeList());
        }
        return authorizationInfo;
    }

    /**
     * 用户登陆认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        UserInfo userInfo = userCacheMap.get(token.getUsername());
        if (null == userInfo) {
            throw new UnknownAccountException("用户不存在");
        }
        return new SimpleAuthenticationInfo(userInfo, userInfo.getPassword(), getName());
    }
}
